package org.ruanjj.multithread.JUC;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

//condition如何进行精确唤醒
//A打印5次唤醒B， B打印10次唤醒C ， C打印5次再唤醒A
//进行5轮
public class ReentrantLockDemo {
    public static void main(String[] args) {
        ShareResource ss = new ShareResource();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                ss.APrint();
            },"A").start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                ss.BPrint();
            },"B").start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                ss.CPrint();
            },"C").start();
        }
    }
}



class ShareResource{
    private int number = 1;
    private ReentrantLock lock  =  new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void APrint(){
        lock.lock();
        try {
            while(number != 1){
                c1.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName()+"打印"+i);
            }
            number = 2;
            c2.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }


    public void BPrint(){
        lock.lock();
        try {
            while(number != 2){
                c2.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName()+"打印"+i);
            }
            number = 3;
            c3.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void CPrint(){
        lock.lock();
        try {
            while(number != 3){
                c3.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName()+"打印"+i);
            }
            number = 1;
            c1.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
